<?php

namespace App\Http\Services;

use App\Http\Repositories\Redis\CacheDataRedis;
use App\Http\Requests\UserContext;
use App\Http\Traits\Errors;
use App\Http\Traits\GlobalConstant;
use App\Models\Article;
use App\Models\Benefit;
use App\Models\Goods;
use App\Models\UserBenefit;
use App\Util\Helper;
use App\Util\TencentMapApiRequest;

class PlatformService extends BaseService
{
    use Errors;

    public function pouchCardPoint()
    {
        $pouchData                   = CacheDataRedis::getRedisInstance()->systemConfig('pouch');
        $pouchData['pouch_distance'] = (int)$pouchData['pouch_distance'];
        return compact("pouchData");
    }

    public function pouchCardPoint2()
    {
        $pouchData             = CacheDataRedis::getRedisInstance()->systemConfig('pouch');
        $circle                = new \stdClass();
        $circle->latitude      = $pouchData['latitude'];
        $circle->longitude     = $pouchData['longitude'];
        $circle->color         = '#69BFBE6A';
        $circle->fillColor     = '#69BFBE6A';
        $circle->radius        = (int)$pouchData['pouch_distance'];
        $circle->strokeWidth   = 2;
        $marker                = new \stdClass();
        $marker->id            = 1;
        $marker->height        = 17;
        $marker->width         = 10;
        $marker->latitude      = $pouchData['latitude'];
        $marker->longitude     = $pouchData['longitude'];
        $callout               = new \stdClass();
        $callout->content      = '打卡范围';
        $callout->color        = '#FFFFFF';
        $callout->fontSize     = 12;
        $callout->borderColor  = '#69BFBE';
        $callout->bgColor      = '#69BFBE';
        $callout->padding      = 5;
        $callout->borderRadius = 3;
        $callout->display      = 'ALWAYS';
        $callout->textAlign    = 'center';
        $marker->callout       = $callout;
        return ['circle' => [$circle], 'marker' => [$marker]];
    }

    public function searchCampusType()
    {
        return GlobalConstant::getSearchCategoryMap();
    }

    public function resourceList()
    {
        $basic = CacheDataRedis::getRedisInstance()->systemConfig('basic') ?? [];
        $rule  = CacheDataRedis::getRedisInstance()->systemConfig('rule') ?? [];
        return compact("basic", "rule");
    }

    public function articleDetail()
    {
        $id = request('article_id') ?? 0;
        return Article::find($id);
    }

    public function qqMapLine()
    {
        if ($cache = CacheDataRedis::getRedisInstance()->get('coords')) {
            return [['points' => json_decode($cache, true), 'color' => '#ff0000', 'width' => 5, 'arrowLine' => true, 'dottedLine' => true]];
        }
        $from              = request('from') ?? '29.486604830668778,106.45813652314246';
        $to                = request('to') ?? '29.54098,106.45773';
        $mapKey            = 'NSLBZ-V7AC2-OAEUM-CTWLI-34ZQV-EZFLS';
        $url               = "https://apis.map.qq.com/ws/direction/v1/driving/";
        $tencentMapService = new TencentMapApiRequest();
        $tencentMapService->setRequestUrl($url);
        try {
            $rel = $tencentMapService->sendRequest(['from' => $from, 'to' => $to, 'output' => 'json', 'callback' => 'cb', 'key' => $mapKey]);
            if ($rel['status'] != 0) {
                $this->showError($rel['message']);
            }
            $coors = $rel['result']['routes'][0]['polyline'];
            for ($i = 2; $i < count($coors); $i++) {
                $coors[$i] = $coors[$i - 2] + $coors[$i] / 1000000;
            }
            for ($i = 0; $i < count($coors); $i += 2) {
                $data[] = ['latitude' => $coors[$i], 'longitude' => $coors[$i + 1]];
            }
            CacheDataRedis::getRedisInstance()->set('coords', json_encode($data));
            return ['points' => $data];
        } catch (\Exception $exception) {
            $this->showError($exception->getMessage());
        }
    }

    public function wechatMessageList()
    {
        $type = request('type') ?? '';
        if (empty($type)) {
            return [];
        }
        switch ($type) {
            case 'bm':
                $arr = [
                    'U5BdigRmMI4dRoZSg9sh5pryRYHbeCK-G-HRiuBbjFM',//预约成功订阅消息
                    'HtCd3_f2R2EUBeffKXm_c9YsUz0yg49E-iwA3s1l3Zw',//日程提醒
                ];
                break;
            default:
                $arr = [];
                break;
        }
        return $arr;
    }

    public function getMapSearch()
    {
        $keyword = request('kw') ?? '';
        $key     = config('admin.extensions.latlong.providers.tencent.api_key');
        $url     = "https://apis.map.qq.com/ws/place/v1/suggestion?key=" . $key . "&keyword=" . $keyword;
        $res     = Helper::http_mini_curl($url);
        $lat     = '';
        $lng     = '';
        if (!empty($res['data'])) {
            $lat = $res['data'][0]['location']['lat'];
            $lng = $res['data'][0]['location']['lng'];
        }
        return compact("lat", "lng");
    }

    public function benefitList(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $field  = ['*'];
        $offset = ($page * $size) - $size;
        $list   = Benefit::where('status', 1)->with(["campusInfo" => function ($q) {
            $q->select(['id', 'name', 'logo']);
        }])->limit($size)->offset($offset)->get($field)->toArray();
        if (!empty($list)) {
            foreach ($list as &$item) {
                $userBenefit          = UserBenefit::where('user_id', $userId)->where('benefit_id', $item['id'])->first();
                $item['user_benefit'] = $userBenefit ? $userBenefit['approve_status'] : 0;
            }
            unset($item);
        }
        return $list;
    }

    public function scoreGoodsList(UserContext $userContext)
    {
        $type      = request('type') ?? 0;//0全部1我可兑换
        $shopId    = request('shop_id') ?? 0;
        $condition = [['qty', '>', 0]];
        if ($type == 1) {
            $userScore   = $userContext->getScore();
            $condition[] = ['score', '<=', $userScore];
        }
        if (!empty($shopId)) {
            $condition[] = ['shop_id', '=', $shopId];
        }
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $field  = ['id', 'title', 'score', 'shop_id', 'pics'];
        $offset = ($page * $size) - $size;
        return Goods::where('status', 1)->where($condition)->with(["shopInfo" => function ($q) {
            $q->select(['id', 'name', 'logo']);
        }])->limit($size)->offset($offset)->get($field);
    }

    public function benefitDetail(UserContext $userContext)
    {
        $id     = request('id') ?? 0;
        $userId = $userContext->getId();
        $detail = Benefit::where('id', $id)->with(["campusInfo" => function ($q) {
            $q->select(['id', 'name', 'logo', 'address', 'contact', 'linkman']);
        }])->first();
        if (!empty($detail)) {
            $userBenefit          = UserBenefit::where('user_id', $userId)->where('benefit_id', $id)->first();
            $detail->user_benefit = $userBenefit ? $userBenefit['approve_status'] : 0;
            $detail->roll_total   = UserBenefit::where('benefit_id', $id)->where('approve_status', 2)->count();
        }
        return $detail;
    }

    public function scoreGoodsDetail(UserContext $userContext)
    {
        $id = request('id') ?? 0;
        return Goods::where('id', $id)->with(["shopInfo" => function ($q) {
            $q->select(['id', 'name', 'logo', 'address', 'longitude', 'latitude', 'contact']);
        }])->first();
    }

}
